param(
	[Parameter(Mandatory=$false)]
	[string]$inputFile="inputlist.txt",     # the input file to store vdi,domain and fid list
	[Parameter(Mandatory=$false)]
	[switch]$inputFileSaved,               # tell if inputfile has been saved, otherwise will popup text to let user enter VDI list.
	[Parameter(Mandatory=$false)]
	[switch]$functionInvoked              # tell if script needs to invoke functions
)
$st=get-date
$this_path = Split-Path -Parent ($MyInvocation.MyCommand.Definition) # get the directory of this running script
$parentPath=(get-item $this_path).Parent.FullName
If( !$functionInvoked ){
	. "$parentPath\functions.ps1" # import functions to powershell from functions.ps1
}
If( $inputFile -notlike "*\*"){
    $inputFile="$this_path\$inputFile"
}
$inputlist=Get-Inputlist $inputFile $inputFileSaved
#-----------------------------------------------AA Client Checking--------------------------------------------------------------
$aaclient_temppath="$this_path\temp" # used to store each result csv file from end vdi incase the script breaks in the middle of running unexpectedly so that we can check the file and know which ones we have already checked
del "$aaclient_temppath\*.csv" -Force -ErrorAction Ignore
del "$this_path\*.csv" -Force -ErrorAction Ignore
New-FileOrFolder $aaclient_temppath -d
$AA_Action={
	param($line,$vdi_cnt,$ActionParams)
	try{$vdi,$domain,$fid,$env=$line.split(",").trim().ToUpper()}catch{}
	$aaclient_temppath,$this_path=$ActionParams
	$aa_pros = [ordered]@{
		"Category/Setting"="$vdi/$fid/$domain";
		"AA/Version"=$null;
		"AA/Username"=$null;
		"AA/Password"=$null;
		"AA/AutoLogin"=$null;
		"AA/ScheduleTasks"=$null;
		"AA/Host"="N";
		"AA/Post"="N";
		"AA/JavaRuntimeEnvironment"=$null;
		"AA/JavaRuntimeEnvironmentList"=$null;
		"AA/IEPlugin"="N";
		"AA/ChromePlugin"="N";
		"AA/JavaPlugin"="N"
	}
	If( [string]::IsNullOrWhiteSpace($fid) -or [string]::IsNullOrWhiteSpace($domain) -or [string]::IsNullOrWhiteSpace($env) ){
		$aa_pros.Set_Item("Category/Setting","$vdi/$fid/$domain(one or more of 'fid,domain,env' has not been provided)")
		$rst= New-Object PSObject -Property $aa_pros ; Write-Host -ForegroundColor Red "$vdi_cnt-$vdi FID Not Provided" ; return $rst
	}
	If(Test-Connection $vdi -quiet -count 1 -ErrorAction Ignore){ # write-host "Checking if $vdi is online"
		write-host "Processing in $vdi_cnt-$vdi for AA Client checking...`n"
		$aa_details=@()
		try{
			Get-Service RemoteRegistry -cn $vdi|?{$_.Status -ieq "Stopped"}|Start-Service
			$reg32_path="\\$vdi\HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{CB6A8B9C-0E2A-4746-B096-438929F00A15}"
			$reg64_path="\\$vdi\HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{CB6A8B9C-0E2A-4746-B096-438929F00A15}"
			If( ($aa_reg_details=reg query $reg32_path 2>$null) -eq $null ){
			    $aa_reg_details=reg query $reg64_path 2>$null
			}
			If( $aa_reg_details -ne $null ){
				$aa_details+=(($aa_reg_details -imatch "\bDisplayVersion\b") -split("REG_SZ"))[-1].trim()
				$aa_details+=("\\$vdi\c$"+(($aa_reg_details -imatch "\bInstallLocation\b") -split("C:"))[-1].trim())
			}
		}catch{
			If($_.exception -like "*Access is denied*"){$aa_pros.Set_Item("Category/Setting","$vdi/$fid/$domain Access denied")}
			$rst= New-Object PSObject -Property $aa_pros ; Write-Host -ForegroundColor Red "$vdi_cnt-$vdi-Access denied" ; return $rst
		}
		If($aa_details.count -eq 2){
			$aa_pros.Set_Item("AA/Version",$aa_details[0])
			$aa_install_location=$aa_details[1]
			#--------------------------------------------------------conect database to check login setting and email setting
			Function Connect-Sql(){
				param
				(
					[Parameter(Mandatory=$True)]
					[string]$DBServer,
					[Parameter(Mandatory=$True)]
					[string]$DBPwd,
					[Parameter(Mandatory=$False)]
					[string]$DBS= "ICGDB"
				)
				$connection = New-Object System.Data.SqlClient.SqlConnection
				$connection.ConnectionString = "Server=$DBServer;uid=aa_dbread;pwd=$DBPwd;Database=$DBS;Integrated Security=False;"
				Try{
				   $connection.Open() ; return $connection
				}Catch{
				   Write-Error "Failed to connect to DB server $DBServer with user 'aa_dbread'!"; return $null
				}Finally{}
			}
			Function Execute-Sql(){
				param(
					[Parameter(Mandatory=$True)]
					$connection,
					[Parameter(Mandatory=$False)]
					[string]$query
				)
				Try{
					$adapter = New-Object System.Data.sqlclient.sqlDataAdapter (new-object system.data.sqlclient.sqlcommand($query,$connection))
					$dataset = New-Object System.Data.DataSet ; $adapter.Fill($dataSet) | Out-Null
					return $dataSet.Tables[0]
				}Catch{
					Write-Error "Failed to run sql syntax $query in $domain $env DB $DBServer"
					return $null
				}Finally{}
			}
			$db_config=[XML](get-content "$this_path\db_config.xml")
			$DBServer = $db_config.SelectSingleNode("//$domain/$env/server").InnerText
			$DBPwd = $db_config.SelectSingleNode("//$domain/$env/pwd").InnerText
			$DBPwd=[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR((ConvertTo-SecureString $DBPwd)))
			$connection=Connect-Sql -DBServer $DBServer -DBPwd $DBPwd
			$user_query = "select id,Name from dbo.Credentials where Name like '%$fid%'"
			If( ($user_db_detail=Execute-Sql -connection $connection -query $user_query) -ne $null){
			    Foreach( $row in $user_db_detail){
					$CredentialId=[int]$row.id
			        If( $row.name -imatch "EmailSettings" ){
						$db_host=$db_config.SelectSingleNode("//$domain/$env/host").InnerText
						$db_port=$db_config.SelectSingleNode("//$domain/$env/port").InnerText
						# write-host "$vdi-$db_host-$db_port--"
						$email_query = "select name,value from dbo.CredentialAttributes where CredentialId = '$CredentialId'"
						If( ($email_db_detail=Execute-Sql -connection $connection -query $email_query) -ne $null){
							Foreach( $row in $email_db_detail){
								If( $row.name -imatch "Host"){
									If( $row.value -imatch [regex]::Escape($db_host)){
										$db_host_value="Y"
									}else{
										$db_host_value="Email host has been set but is not 'imta.citicorp.com'($($row.value))"
									}
									$aa_pros.Set_Item("AA/Host",$db_host_value)
								}elseif($row.name -imatch "Port"){
									If( $row.value -imatch [regex]::Escape($db_port)){
										$db_port_value="Y"
									}else{
										$db_host_value="Email port has been set but is not 25($($post.value))"
									}
									$aa_pros.Set_Item("AA/Post",$db_port_value)
								}
							}
						}
			        }elseif($row.name -imatch "LoginSettings"){
			            $aa_pros.Set_Item("AA/Username","$domain\$fid")
			            $aa_pros.Set_Item("AA/Password","********")
			        }
			    }
			}
			#--------------------------------------------------------close connection to the database
			$connection.close() # close db connections
			# get user AA setting XML file
			$AAsettingFile="\\$vdi\C$\Users\$fid\Documents\Automation Anywhere Files\AA.Settings.xml"
			If( !(test-path $AAsettingFile) ){
				$aa_pros.Set_Item("AA/AutoLogin","Not found AA.Settings.xml")
			}else{
				$AA_settings = [XML](get-content (Get-Item -Path $AAsettingFile).FullName)
				#<------------------------------- get 'Auto Login Your Computer For When Tasks Run'
				$aa_pros.Set_Item("AA/AutoLogin",$AA_settings.SelectSingleNode("//options/autologin/autologin").InnerText)
				#<------------------------------- get 'Scheduling for Tasks'
				$aa_pros.Set_Item("AA/ScheduleTasks",$AA_settings.SelectSingleNode("//options/autologin/scheduletask").InnerText)
				#<------------------------------- get 'Java Settings: Java Runtime Environment For Application'
				$aa_pros.Set_Item("AA/JavaRuntimeEnvironment",$AA_settings.SelectSingleNode("//javasettings/selected/path").InnerText)
				#<------------------------------- get 'Java Settings: Java Runtime Environment List'
				$jrel_path=$AA_settings.SelectNodes("//javasettings/item/path").InnerText ; $cnt=$jrel_path.count
				$jrel_bit=$AA_settings.SelectNodes("//javasettings/item/bit").InnerText ; $jrel=$null
				For( $n=0; $n -lt $cnt; $n++ ){
					$jrel_path_temp=$jrel_path[$n]
					$jrel_bit_temp=$jrel_bit[$n]
					$jrel += "$jrel_path_temp-$jrel_bit_temp|"
				}
				$aa_pros.Set_Item("AA/JavaRuntimeEnvironmentList",$jrel)
				#<------------------------------- GET AA PLUGINS------------------------------->#
				#<------------------------------- check Plugin Settings: IE
				$sid = (New-Object System.Security.Principal.NTAccount("$domain\$fid")).Translate([System.Security.Principal.SecurityIdentifier]).value
				$iedll="$aa_install_location\Client\Automation.InternetExplorerAddIn.DLL"
				$ieflags=Switch -regex ((reg query "\\$vdi\HKU\$sid\Software\Microsoft\Windows\CurrentVersion\Ext\Settings\{8A194578-81EA-4850-9911-13BA2D71EFBD}" /v flags) -imatch 'flags' 2>$null){
					"REG_DWORD"{[convert]::toint32(($_ -split("REG_DWORD"))[-1].trim(),16) ; break}
					"REG_QWORD"{[convert]::toint64(($_ -split("REG_QWORD"))[-1].trim(),16)}
				}
				If( (test-path $iedll) -and ($ieflags -ne 1)){$aa_pros.Set_Item("AA/IEPlugin","Y")}
				#<------------------------------- check Plugin Settings: Chrome
				$chrome_extension="\\$vdi\C$\Users\$fid\AppData\Local\Google\Chrome\User Data\Default\Extensions\jkppbemeojeacdkknnbpbaedpdmgidho"
				If( test-path $chrome_extension -ea 0){
					$version=(ls $chrome_extension).name
					$manifest_file="$chrome_extension\$version\manifest.json"
					If( (test-path $manifest_file) -and ((cat $manifest_file) -imatch "Automation Anywhere")){
						$aa_pros.Set_Item("AA/ChromePlugin","Y")
					}
				}
				#<------------------------------- check Plugin Settings: Java
				$AAlib1="$aa_install_location\Client\Automation.JavaAccessBridge64.dll"
				$AAlib2="$aa_install_location\Client\WindowsAccessBridge-32.dll" # to be double confirmed
				If( (test-path $AAlib1) -and (test-path $AAlib2) ){$aa_pros.Set_Item("AA/JavaPlugin","Y")}
			}
		}else{
		    $aa_pros.Set_Item("Category/Setting","$vdi/$fid/$domain-Not found AA registry")
			$rst= New-Object PSObject -Property $aa_pros ; Write-Host -ForegroundColor Red "$vdi_cnt-$vdi-Not found AA registry" ; return $rst
		}
	}else{
		$aa_pros.Set_Item("Category/Setting","$vdi-invalid name or offline/$fid/$domain")
	}
	$rst= New-Object PSObject -Property $aa_pros
	Write-Host -ForegroundColor Yellow "----$vdi_cnt-$vdi Done check AA Client info----`n"
	$rst|Export-Csv -Path "$aaclient_temppath\$vdi-AAClient.csv" -UseCulture -NoTypeInformation -Encoding UTF8 -Force -ErrorAction Ignore
	return $rst
}
$aa_client_settings = Start-BulkThreads $inputlist $AA_Action $aaclient_temppath,$this_path 100|sort "Category/Setting"
Export-Result $aa_client_settings "aa_client_settings" "$this_path\aa.csv" ([math]::Round(((get-date)-$st).totalseconds))
